<template>
  <div class="MarkdownViewer">
    <div class="markdown-body" ref="mdRef"></div>
    <div class="btn" v-if="isOk">
      <el-button
        type="text"
        @click="goToTheEditor"
      >
        转编辑器
      </el-button>
    </div>
    <el-drawer
      :title="title"
      :visible.sync="showDrawer"
      :direction="'rtl'"
      size="50vw"
    >
      <div class="showEditorDi">
        <div class="btn">
          <el-button
            type="primary"
            @click="exportDoc"
          >
            导出
          </el-button>
        </div>
        <Wangeditor
          class="markdown-body"
          ref="EditorRef"
          v-model="editorValue"
        ></Wangeditor>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import $ from 'jquery'
import MarkdownIt from 'markdown-it'
import {markdownItTable} from 'markdown-it-table'
import markdownItContainer from 'markdown-it-container'
import * as echarts from 'echarts'
import { MarkdownRender } from './MarkdownRenderUtils'
//将html转为word
import { asBlob } from 'html-docx-js-typescript'
import Wangeditor from '@/components/Wangeditor/Wangeditor.vue'

let md = new MarkdownIt().use(markdownItTable)
let tmpDiv = document.createElement('div')
tmpDiv.className = 'markdown-body'

markdownItContainer(md, 'echarts', {
  validate: (params) => {
    return params.trim().startsWith('echarts')
  },
  render: (tokens, idx) => {
    let m = tokens[idx].info.trim().match(/^echarts(.*)$/)
    if (tokens[idx].nesting === 1) {
      // opening tag
      return `<div class="echarts_class">` + md.utils.escapeHtml(m[1]) + '\n'
    } else {
      // closing tag
      return '</div>\n'
    }
  }
})

export default {
  name: 'MarkdownViewer',
  props: {
    content:{
      type: String,
      default: ''
    },
    title:{
      type: String,
      default: ''
    },
    isOk: {
      type: Boolean,
      default: false
    },
  },
  components: {
    Wangeditor
  },
  data() {
    return {
      visibleMenu: false,
      selectedText: '',
      showDrawer: false,
      editorValue: ''
    }
  },
  mounted() {
    this.markDownMd = new MarkdownRender(md,this.$refs.mdRef,tmpDiv,['__echartsInstance__'])
    this.$watch(()=>this.content,(val = '')=>{
      if(!val) {
        this.$refs.mdRef.innerHTML = ''
      } else {
        this.markDownMd.rendMd(val,this.renderEcharts)
      }
    },{immediate: true})
  },
  methods: {
    // 下载为word文档函数
    async exportDoc() {
      // 将富文本内容拼接为一个完整的html
      const html = this.editorValue
      const value = `<!DOCTYPE html>
  <html lang="zh-CN">
    <head>
      <meta charset="UTF-8">
      <title>文档</title>
      <style>
        img{
            max-width: 100%;
          }
      </style>
    </head>
    <body>
        ${html}
    </body>
  </html>`
      //  landscape就是横着的，portrait是竖着的，默认是竖屏portrait。
      const data = await asBlob(value, { orientation: 'portrait' })
      const a = document.createElement('a')
      a.href = window.URL.createObjectURL(data)
      a.setAttribute('download', `${this.title ? this.title : '智能生成文档'}.docx`)
      a.click()
      // 下载后将标签移除
      a.remove()
    },
    /**
     * md转富文本
     */
    goToTheEditor() {
      this.showDrawer=true
      let nodeDeepClone = this.$refs.mdRef.cloneNode(true)
      let echartsEls = nodeDeepClone.getElementsByClassName('echarts_class')
      let echartsElsOld = Array.from(this.$refs.mdRef.getElementsByClassName('echarts_class'))
      Array.from(echartsEls).forEach((el,index) => {
        let elOld = echartsElsOld[index]
        let ech = elOld.__echartsInstance__
        let imageElement = document.createElement('img')
        $(imageElement).css("max-width","100%")
        let dataURL = ech.getDataURL({
          type: 'png',
          backgroundColor: '#FFFFFF',
          pixelRatio: 1
        })
        let p = document.createElement('p')
        imageElement.src = dataURL
        p.appendChild(imageElement)
        el.replaceWith(p)
      })
      // 处理ol转成wangeditor可用的形式
      let lis = $(nodeDeepClone).find("ol>li")
      lis.each((index, li)=>{
        let ul = $(li).find(">ul")
        ul.insertAfter(li)
        let p = $(li).find('>p')
        $(li).html(p.html())
      })
      this.editorValue=nodeDeepClone.innerHTML
    },
    renderEcharts() {
      this.$nextTick(() => {
        let echartsEls = this.$refs.mdRef.getElementsByClassName('echarts_class')
        Array.from(echartsEls).forEach(el => {
          let data = el.innerText.trim()
          if(!data || el.__echartsInstance__) {
            return
          }
          try {
            data = JSON.parse(data)
            if(data.elStyle){
              el.style = data.elStyle
            }
            if(data.echartsOptions) {
              let instance = echarts.init(el)
              el.__echartsInstance__ = instance
              instance.setOption(data.echartsOptions)
            }
          }catch (e){}
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.MarkdownViewer{
  background: white;
}
.markdown-body {
  ::v-deep {
    ul {
      list-style-type: disc; /* 设置为实心圆 */
    }

    ul li::marker {
      color: rgb(22, 21, 21); /* 将项rgb(19, 18, 18)颜色改为红色 */
    }
    .echarts_class{
      height: 300px;
    }
  }
}
.btn{
  display: flex;
  justify-content: flex-end;
}
.showEditorDi{
  padding: 20px;
  height: 100%;
  padding-top: 0;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  .editor{
    flex: 1;
    overflow: auto;
  }
  .Wangeditor{
    flex: 1;
    overflow: auto;
  }
}
</style>
